//
//  WFComposePictureView.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/18.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit
//  重用标记
private let WFComposePictureViewCellIdentifier = "WFComposePictureViewCellIdentifier"
class WFComposePictureView: UICollectionView {

    // MARK:  - 定义数据源存储图片
   lazy var images = [UIImage]()
    //点击加号的闭包
    var clickOnAddBtnClosure:(()->())?
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayOut = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayOut)
        setUpUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:  - 添加控件
    private func setUpUI(){
        backgroundColor = RandomColor()
        
        registerClass(WFComposePictureViewCell.self, forCellWithReuseIdentifier: WFComposePictureViewCellIdentifier)
        
        dataSource = self
        delegate = self
        
        hidden = true
    }
    
    
    
    // MARK:  - 对外暴露的添加image的方法
    func addImage(image:UIImage){
        hidden = false
        images.append(image)
        reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  每项之间的间距
        let itemMargin: CGFloat = 5
        //  每项大小
        let itemWidth = (width - 2 * itemMargin) / 3
        
        //  设置大小和间距
        //  获取布局方式
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  设置垂直间距
        flowLayout.minimumLineSpacing = itemMargin
    }
    

}

// MARK:  - 实现collectionview数据源方法
extension WFComposePictureView:UICollectionViewDelegate,UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 9 || images.count == 0 {
        return images.count
        } else {
        return images.count + 1
        }
        

    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WFComposePictureViewCellIdentifier, forIndexPath: indexPath) as! WFComposePictureViewCell
        if indexPath.item == images.count {
            cell.image = nil
        } else {
         cell.image = images[indexPath.item]
        }
        
        //设置cell上的闭包
        cell.deleteBtnClosure = {
            self.images.removeAtIndex(indexPath.item)
            //如果没有数据就隐藏
            if self.images.count == 0 {
                self.hidden = true
            }
            //  重新加载数据
            self.reloadData()
        }
        
       
        
        return cell
        
    }
    
    //点击cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.item == images.count {
        //说明是最后一个
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            clickOnAddBtnClosure?()
        
        }
    }
}

// MARK:  - 直接定义cell
class WFComposePictureViewCell:UICollectionViewCell {

    // MARK:  - cell上控件的懒加载
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    // MARK:  - 定义删除闭包
    var deleteBtnClosure:(()->())?
    //  删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:  - 对cell进行初始化
    private func setUpUI(){
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }

    
    }
    
    // MARK: --点击事件
    @objc private func deleteButtonAction() {
        //点击删除按钮的时候执行闭包
        deleteBtnClosure?()
        
    }

    
    //定义image属性
    var image:UIImage?{
        didSet {
            if image == nil {
                 deleteButton.hidden = true
                imageView.image = UIImage(named:"compose_pic_add" )
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
            }else{
                //  设置选中的图片
                imageView.image = image
                //  显示删除按钮
                deleteButton.hidden = false
                //  取消高亮效果
                imageView.highlightedImage = nil
            }
        }
    }
}
